#!/bin/bash

# 定义颜色变量以增强可读性
GREEN='\033[0;32m'  # 绿色
RED='\033[0;31m'    # 红色
NC='\033[0m'        # 恢复默认颜色

# 定义变量和配置
mavenCommand=$(which mvn)
javaCommand=$(which java)
cpCommand=$(which cp)
gitCommand=$(which git)
logFile="deploy.log"
app="kong-new.jar"
projectDir="Integration_space_new"
sourceJarPath="ruoyi-admin/target/ruoyi-admin.jar"
jvmOpt="-Dfile.encoding=UTF-8"
springbootOpt="--server.port=8080"

# 函数：执行 Git 命令
function git_command() {
    local repoDir=$1
    local gitArgs=$2
    git_version=$($gitCommand --version | awk '{print $3}')
    major_version=$(echo "$git_version" | cut -d. -f1)
    minor_version=$(echo "$git_version" | cut -d. -f2)
    patch_version=$(echo "$git_version" | cut -d. -f3)
    if (( major_version < 1 || (major_version == 1 && minor_version < 8) || (major_version == 1 && minor_version == 8 && patch_version < 5) )); then
        currentDir=$(pwd)
        cd "$repoDir" || exit 1
        $gitCommand $gitArgs
        cd "$currentDir" || exit 1
    else
        $gitCommand -C "$repoDir" $gitArgs
    fi
}

# 函数：停止应用
function stop_application() {
    local pid=$(pgrep -f "$app")  # 查找匹配进程
    if [ -n "$pid" ]; then
        echo -e "${GREEN}Stopping application with PID: $pid...${NC}"
        echo "$(date) - Stopping the application with PID: $pid" >> "$logFile"
        # 发送 SIGTERM 信号终止进程
        kill -15 "$pid"
        sleep 5  # 等待一段时间
        # 检查进程是否仍在运行
        if ps -p "$pid" > /dev/null; then
            # 如果进程仍在运行，发送 SIGKILL 终止进程
            echo -e "${RED}Forcefully terminating application...${NC}"
            kill -9 "$pid"
        fi
    else
        echo -e "${GREEN}No matching application process found.${NC}"
        echo "$(date) - No matching application process found." >> "$logFile"
    fi
}


# 函数：更新代码
function update_code() {
    echo -e "${GREEN}Updating code from repository...${NC}"
    git_command "$projectDir" pull
    echo "$(date) - Updated code from repository" >> "$logFile"
}

# 函数：编译项目
function compile_project() {
    echo -e "${GREEN}Compiling the project...${NC}"
    $mavenCommand -f "$projectDir/pom.xml" clean package -Dmaven.test.skip=true  
    echo "$(date) - Compiled the project" >> "$logFile"
}

# 函数：复制 JAR 文件
function copy_jar_file() {
    echo -e "${GREEN}Copying JAR file...${NC}"
    $cpCommand "$projectDir/$sourceJarPath" "$app"
    echo "$(date) - Copied JAR file" >> "$logFile"
}

# 函数：启动应用
function start_application() {
    echo -e "${GREEN}Starting the application...${NC}"
    nohup $javaCommand -jar $jvmOpt "$app" $springbootOpt >> ${app}.log 2>&1 &
    echo "$(date) - Started the application" >> "$logFile"
}

# 主要流程
{
    stop_application &&
    update_code &&
    compile_project &&
    copy_jar_file &&
    start_application
} || {
    echo -e "${RED}$(date) - Deployment failed${NC}" >> "$logFile"
    exit 1
}
